<?php
/**
 * Description of Request
 *
 * @author joona
 */
class Core_Request
{
    private $baseUri;
    private $getParameters;
    private $postParameters;

    private $validationRules;
    
    public function  __toString()
    {
        return 'Core_Request';
    }

    /**
     * Set validation/format rules to multiple variables
     * $rules are given in format:
     * array(
     *      'nameOfVar' => array('type' => ... , 'regexp' => ... ),
     *      'anotherVar' => array('type' => ... , 'regexp' => ... )
     * )
     * @param $rules Array of variableName - rules pairs
     */
    public function setValidationRules($rules)
    {
        foreach ($rules as $varName => $rule)
            Core_Validator::setRule($varName, $rule);
    }

    /**
     * Set validation/format rules to a variable
     *
     * Supported rules are:
     *      type, allowNull, minLength, maxLength, minValue, maxValue, regexp
     * For example:
     * $db->setRule('userID', array(
     *      'type' => 'integer', //integer, double, string, bool
     *      'minValue' => 1
     * ));
     *
     * @param $name Name of the variable rules apply to
     * @param $rule Array of validation/format rules
     */
    public function setValidationRule($name, $rule)
    {
        Core_Validator::setRule($varName, $rule);
    }

    /**
     * Remove all rules from database handler
     */
    public function resetValidationRules()
    {
        Core_Validator::resetRules();
        Core_Validator::resetErrors();
    }


    /**
     * Constructor, init private variables
     * @param string $baseUri
     * @param array $get GET parameters parsed from request
     */
    public function  __construct($baseUri, $get = array(), $post = array())
    {
        $this->baseUri = $baseUri;
        $this->getParameters = $get;
        $this->postParameters = $post;
    }

    /**
     * Getter for baseUri of the request
     * @return string $baseUri
     */
    public function getBaseUri()
    {
        return $this->baseUri;
    }

   /**
     * Get a GET parameter from request
     * If no $key is provided, return all post parameters as an array
     * Return null if no parameter with given key is found
     * @param string $key Key of GET parameter to return
     * @return misc
     */
    public function getGetData($key = null)
    {
        if(is_null($key))
        {
            return $this->returnIfValid ($this->getParameters);
        }
        else if(isset($this->getParameters[$key]))
            return $this->returnIfValid ($this->getParameters[$key], $key);
        else
            return null;
    }

    /**
     * Get a POST parameter from request
     * If no $key is provided, return all post parameters as an array
     * Return null if no parameter with given key is found
     * @param string $key Key of POST parameter to return
     * @return misc
     */
    public function getPostData($key = null)
    {
        if(is_null($key))
            return $this->returnIfValid ($this->postParameters);
        else if(isset($this->postParameters[$key]))
            return $this->returnIfValid ($this->postParameters[$key], $key);
        else
            return null;
    }

    /**
     * Returns $variable if Core_Validator approves it
     * @param MISC $variable
     * @param STRING $key
     * @return MISC
     */
    private function returnIfValid($variable, $key = null)
    {
        if(is_array($variable) && !Core_Validator::validateVariables($variable))
        {
            throw new Core_Request_Exception(
                    'Validation failed: '.implode (', ', Core_Validator::getErrors())
            );
        }
        else if(!is_array($variable) && !Core_Validator::validate($key, $variable))
        {
            throw new Core_Request_Exception(
                    'Validation failed: '.implode (', ', Core_Validator::getErrors())
            );
        }
        else
            return $variable;

    }

    /**
     * Goes trough Post and Get parameters and replaces empty strings with nulls
     */
    public function replaceEmptyStringsWithNulls()
    {
        foreach ($this->postParameters as $index => $value)
                $this->postParameters[$index] = strlen ($value) == 0 ? null : $value;

        foreach ($this->getParameters as $index => $value)
                $this->getParameters[$index] = strlen ($value) == 0 ? null : $value;
    }
}
class Core_Request_Exception extends Exception { }